package sisi.broker;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;
import sisi.bank.Bank;
import sisi.bank.BankController;
import sisi.ports.Port;
import sisi.ports.PortController;
import sisi.yacht.YachtsWindow.BankItemRenderer;


/**
 * BrokerWindow.java - Controller class for <i>Broker window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 29/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class BrokerWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxBroker
	private Window windowBroker, windowEditBroker;
	private Textbox tbCerca;
	private Listbox boxBroker;

	private List tutti_i_broker;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object brokerItem;
	private Broker modBroker;
	// edit
	private Intbox id;
	private Textbox desc_, tel, fax, email, gsm, contact, address, city, country, port;
	private Listbox portlist;

	public void onCreate$windowBroker(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutti_i_broker = new BrokerController().getBrokerList(null);
		listModelList.addAll(tutti_i_broker);
		boxBroker.setModel(listModelList);
		boxBroker.setItemRenderer(new BrokerItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutti_i_broker.size(); i++) {
				Broker broker = (Broker)tutti_i_broker.get(i);
				if (broker.getId()==idSelezionato.intValue()){
					boxBroker.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutti_i_broker = new BrokerController().getBrokerList(tbCerca
				.getValue());
		listModelList.addAll(tutti_i_broker);
		boxBroker.setModel(listModelList);
		boxBroker.setItemRenderer(new BrokerItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxBroker.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oBroker = boxBroker.getSelectedItem().getAttribute(
					"rigaBroker");
			String codiceSelezionato = ""+((Broker) oBroker).getId();
			Sessions.getCurrent().setAttribute("codiceBrokerSelezionato",
					codiceSelezionato);
			windowBroker.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxBroker.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Broker to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxBroker", boxBroker);
				Window finestraEditBroker = (Window) Executions.createComponents(
						"/editBroker.zul", null, map);
				finestraEditBroker.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class BrokerItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Broker) data).getId()).setParent(li);
			new Listcell(((Broker) data).getDesc()).setParent(li);
			li.setAttribute("rigaBroker", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT BROKER: NEW/MODIFY
	public void onCreate$windowEditBroker(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxBroker = (Listbox) args.get("boxBroker");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		
		listModelList = new ListModelList();
		List<Port> tutti_i_ports = new PortController().getPortList(null);
		listModelList.addAll(tutti_i_ports);
		portlist.setModel(listModelList);
		portlist.setItemRenderer(new PortItemRenderer());		

		
		
		if (!lNuovo) {
			brokerItem = boxBroker.getSelectedItem().getAttribute("rigaBroker");
			modBroker = new BrokerController().refreshBroker((Broker) brokerItem);
			brokerItem = modBroker;
			windowEditBroker.setTitle("Edit Broker");
			desc_.setFocus(true);
			id.setValue(modBroker.getId());
			desc_.setValue(General.toUpperAncheNull(modBroker.getDesc() ) );
			tel.setValue(modBroker.getTel());
			fax.setValue(modBroker.getFax());
			email.setValue(modBroker.getEmail());
			gsm.setValue(modBroker.getGsm());
			contact.setValue( General.toUpperAncheNull( modBroker.getContact() ) );
			address.setValue( General.toUpperAncheNull( modBroker.getAddress() ) );
			city.setValue( General.toUpperAncheNull( modBroker.getCity() ) );
			country.setValue( General.toUpperAncheNull( modBroker.getCountry() ) );
			//port.setValue(modBroker.getPort());
			
			if (modBroker.getPort()!=null && Integer.valueOf( modBroker.getPort())!=null && Integer.valueOf( modBroker.getPort() ) > 0 ){
				Port ba = new PortController().getPortxId( Integer.valueOf( modBroker.getPort() ) );
				for (int i = 0; i < listModelList.getSize(); i++) {
					Port ba2 = (Port)listModelList.get(i);
					if (ba2.getId().equals(ba.getId())){
						portlist.setSelectedIndex(i);
						break;
					}
				}
			} else {
				portlist.setSelectedIndex(-1);
			}
			
		} else {
			windowEditBroker.setTitle("New Broker");
			desc_.setFocus(true);
		}
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditBroker.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modBroker = new Broker();
		} else {

		}
		String testoMsg = "";
	
		modBroker.setId(id.getValue());
		modBroker.setDesc(desc_.getValue().toUpperCase());
		modBroker.setTel(tel.getValue());
		modBroker.setFax(fax.getValue());
		modBroker.setEmail(email.getValue());
		modBroker.setGsm(gsm.getValue());
		modBroker.setContact(contact.getValue().toUpperCase());
		modBroker.setAddress(address.getValue().toUpperCase());
		modBroker.setCity(city.getValue().toUpperCase());
		modBroker.setCountry(country.getValue().toUpperCase());
		//modBroker.setPort(portlist.getSelectedItem().getLabel());
		
		// nel elenco dei brokers, nel campo port viene salvato l'id del porto e non il nome del porto
		String porto = "";
		if (portlist.getSelectedItem()!=null){
			
			Object oPo = portlist.getSelectedItem().getAttribute("rigaPort");
			Port po = (Port)oPo;		
			porto = ""+po.getId();
		}
		modBroker.setPort(porto);
		
		if (lNuovo){
			new BrokerController().addBroker(modBroker);
			testoMsg = "Adding Broker: "+ General.trimNull( modBroker.getDesc() );
		} else {
			new BrokerController().updateBroker(modBroker);
			testoMsg = "Updating Broker: "+ General.trimNull( modBroker.getDesc() );			
		}
		
		General.showNotify( testoMsg, windowEditBroker);
		
		windowEditBroker.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxBroker.getListModel();
			lml.add(modBroker);
			boxBroker.setSelectedIndex(lml.indexOf(modBroker));
		} else {
			ListModelList lml = (ListModelList) boxBroker.getListModel();
			Object oBrokerItem = boxBroker.getSelectedItem().getAttribute("rigaBroker");
			if (lml.indexOf(oBrokerItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oBrokerItem), modBroker);
			}
		}		
	}
	
	
	public class PortItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(((Port) data).getPortname()).setParent(li);
			li.setAttribute("rigaPort", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
}
